package com.gdufe.studytogether.config;

import com.gdufe.studytogether.domain.pojo.User;
import com.gdufe.studytogether.utils.UserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class MyInterceptor implements HandlerInterceptor {  
  
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals("OPTIONS")){
            return true;
        }
        //在执行controller方法（handler之前进行执行
        /**
         * 需要判断请求的接口路径是否为handlermethod（controller方法
         */
        if (!(handler instanceof HandlerMethod)) {
            //handler可能是requestresourcehandler springboot程序 访问静态资源 默认classpath下的static目录
            return true;
        }
        User user = (User) request.getSession().getAttribute("userLogin");
        //没有获取到则没有登录
        if (user == null){
            response.setStatus(401);
            return false;
        }
        Integer userId = user.getId();
        UserThreadLocal.put(userId);
        return true; // 返回true表示继续向下执行，返回false则中断执行。
    }  
  
    @Override  
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {  
        // 在请求处理之后，但在视图渲染之前进行拦截  
    }
  
    @Override  
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {  
        // 在整个请求结束之后进行拦截，即在DispatcherServlet渲染了对应的视图之后执行。

        //清除
        UserThreadLocal.remove();
    }
}
